<?php
require '../model/Db.php';
require '../model/Page.php';
$Db = DB::getInstance();
$user_data = $Db->islogin();
$user_data['sex'] = $user_data['sex']?'男':'女';
if(is_string($_GET['type'])){
    setcookie('reqtype',$_GET['type'],time()+3600,'/nsbbs/');
    $path = PHOTO_PATH;
switch ($_GET['type']) {
	case 'home':
	$count = $Db->count([
		table => ['content'],
		where => "`uid` = {$user_data['id']}"
	]);
    if($user_data['lv']>=700){
        $lv = 'lv-7';
    }elseif($user_data['lv']>=580){
        $lv = 'lv-6';
    }elseif($user_data['lv']>=460){
        $lv = 'lv-5';
    }elseif($user_data['lv']>=340){
        $lv = 'lv-4';
    }elseif($user_data['lv']>=220){
        $lv = 'lv-3';
    }elseif($user_data['lv']>=100){
        $lv = 'lv-2';
    }else{
        $lv = 'lv-1';
    }
    $user_data = $Db->tohtml($user_data);
    $logintime = date('Y-m-d H:i:s',$user_data['last_time']);
		$html = <<<html
		<div id="my-home">
            <div class="tt">基本信息</div>
            <div class="main">
                <div>
                    <em>昵称：</em>
                    <span>{$user_data['nick']}</span>
                </div>
                <div>
                    <em>性别：</em>
                    <span>{$user_data['sex']}</span>
                </div>
                <div>
                    <em>绑定邮箱：</em>
                    <span>{$user_data['email']}</span>
                </div>
                <div>
                    <em>联系电话：</em>
                    <span>{$user_data['phone']}</span>
                </div>
            </div>
        </div>
        <div class="live-info">
            <div class="tt">活跃概况</div>
            <div class="main">
                <div>
                    <em>发帖数：</em>
                    <span>{$count}</span>
                </div>
                <div>
                    <em>等级：</em>
                    <span id="lv" class="{$lv}" title="查看等级规则"></span>
                </div>
                <div>
                    <em>最近上站时间：</em>
                    <span>{$logintime}</span>
                </div>
            </div>
        </div>
html;
		break;

	case 'selfmail':
    $cnt = $Db->count([
        table => [mail => 'a',bbs_user => 'b'],
        where => "a.from_id = b.id and a.to_id = {$user_data['id']}"
    ]);
    $page = page($cnt,PAGE_SIZE,PAGE_BTN_CNT);
    $mail_data = $Db->find([
        table => [mail => 'a',bbs_user => 'b'],
        field => 'a.*,b.id uid,b.user,b.photo',
        where => "a.from_id = b.id and a.to_id = {$user_data['id']} order by a.is_read,a.time desc {$page['limit']}"
    ]);
    $mail_data = $Db->tohtml($mail_data);
    if($mail_data){
        foreach ($mail_data as $mail_item) {
            $img = '';
        if($mail_item['photo']){
                $img = <<<img
        <a target="_blank" href="userinfo.php?uid={$mail_item['uid']}"><img class="img-yuan-x36" src="{$path}{$mail_item['photo']}"></a>
img;
        }
        $noread = $mail_item['is_read'] == 0? 'noread':'';
		$body .= <<<body
            <div class="list-item hand clearfix {$noread}">
                <a target="_blank" href="mailcont.php?mailid={$mail_item['id']}" class="link"></a>
                <div class="l title">
                    <span class="sixin-label">标题：</span>
                    {$mail_item['title']}
                </div>
                <div class="l author">
                    <span class="sixin-label">来自：</span>
                    {$img}
                    <span class="username">{$mail_item['user']}</span>
                </div>
                <div class="l time">
                    <span class="sixin-label">时间：</span>
                    {$mail_item['time']}
                </div>
            </div>
body;
        }
        $html = '<div id="sixin">'.$body.'</div>';
    }else{
        $html = '暂时没有私信内容';
    }
    $page_btn = <<<page
                <ul class="pagination">
                {$page['html']}
                </ul>
                <script>
                //分页
                let con_main = $('.nav-content');
                let page_btn = $('.pagination a');
                page_btn.click(function(e){
                    e ? e.preventDefault() : window.e.returnValue = false;
                    $.ajax({
                        url: $(this).prop('href'),
                        type: 'GET',
                        dataType: 'html' 
                    })
                    .done(function(data) {
                        con_main.html(data)
                    });
                });
                </script>
page;
        $html .= $page_btn;
		break;

	case 'mycont':
        $cnt = $Db->count([
            table => ['content'],
            where => "uid = {$user_data['id']} and delete_time is NULL"
        ]);
        $page = page($cnt,PAGE_SIZE,PAGE_BTN_CNT);
        $mycont_data = $Db->find([
            table => ['content'],
            where => "uid = {$user_data['id']} and delete_time is NULL order by time desc {$page['limit']}"
        ]);
        $mycont_data = $Db->tohtml($mycont_data);
        $header = <<<header
            <div class="list-title clearfix">
                <div class="l myaction">操作</div>
                <div class="l mytitle">标题</div>
                <div class="l mytime">发布时间</div>
                <div class="l myreply">回复</div>
                <div class="l mylast">最后发表</div>
            </div>
header;
    foreach ($mycont_data as $mycont_item) {
        //最后发表
        if($mycont_item['cid'] == 0){//主题帖
            $where = "a.uid = b.id and a.cid = {$mycont_item['id']}";
        }else{
            $where = "a.uid = b.id and a.reply_id = {$mycont_item['id']}";
        }
        $last_data = $Db->find([
            table => [content => 'a',bbs_user => 'b'],
            field => 'a.time,b.user,a.id',
            where => $where.' and a.delete_time is NULL order by a.time desc limit 0,1'
        ])[0];
        $mylast = '';
        if($last_data){
            $count = $Db->count([
                table => ['content'],
                where => "id = {$mycont_item['id']} or cid = {$mycont_item['id']}"
            ]);
            $max_page=ceil($count/PAGE_SIZE);
            $last_data = $Db->tohtml($last_data);
            $mylast = <<<last
            <div class="l mylast clearfix">
                <a target="_blank" href="details.php?cid={$mycont_item['id']}&page={$max_page}#end" class="link"></a>
                <div class="l user-time">
                    <div class="iuser">{$last_data['user']}</div>
                    <div class="time">{$last_data['time']}</div>
                </div>
            </div>
last;
        }
		$body .= <<<body
            <div class="list-item hand clearfix">
                <a target="_blank" href="details.php?cid={$mycont_item['id']}" class="link"></a>
                <div class="l myaction">
                    <a target="_blank" href="publish.php?w=update&m={$mycont_item['mid']}&c={$mycont_item['id']}">修改</a>
                    <a href="javascript:{$mycont_item['id']};">删除</a>
                </div>
                <div class="l mytitle">
                    {$mycont_item['title']}
                </div>
                <div class="l mytime">
                    {$mycont_item['time']}
                </div>
                <div class="l myreply">{$mycont_item['reply_num']}</div>
                {$mylast}
            </div>
       
body;
    }
        if(!$mycont_data){
            $body = '<span>还没有发布过的帖子</span>';
        }
        $page_btn = <<<page
                <ul class="pagination">
                {$page['html']}
                </ul>
                <script>
                //分页
                let con_main = $('.nav-content');
                let page_btn = $('.pagination a');
                page_btn.click(function(e){
                    e ? e.preventDefault() : window.e.returnValue = false;
                    $.ajax({
                        url: $(this).prop('href'),
                        type: 'GET',
                        dataType: 'html' 
                    })
                    .done(function(data) {
                        con_main.html(data)
                    });
                });
                </script>
page;
        $html = $header.$body.$page_btn;
		break;

	case 'follow':
		$a = <<<a
        <div id="guanzhu-collect">
            <div class="i-guanzhu">
                <div class="title">我关注的人<b class="r pull"></b></div>
                <div class="content row">
a;
$follow = json_decode($user_data['my_follow'])->uids;
if(!$follow){
	$b = <<<b
			<div class="no-content">
                空空如也
            </div>
b;
}else{
	$follow_uids = implode(',', $follow);
	$data1 = $Db->find([
		table => ['bbs_user'],
		where => "`id` in ($follow_uids)"
	]);
	foreach ($data1 as $item) {
    //状态
	$stat1 = (time()-$item['last_time'])<1800 ? 'online':'offline';
    //关注、粉丝
    $guanzhu1 = count(json_decode($item['my_follow'])->uids);
    $fensi1 = count(json_decode($item['follow_me'])->uids);
    //发帖数
    $count1 = $Db->count([
        table => ['content'],
        where => "`uid` = {$item['id']}"
    ]);
    //获取最新发帖
    $newcont1 = $Db->find([
        table => ['content'],
        field => 'title,time,id',
        where => "uid = {$item['id']} order by time desc"
    ])[0];
    $newcont1['title'] = htmlspecialchars($newcont1['title']);
    $item = $Db->tohtml($item);
$b .= <<<b
                  		<div class="col-sm-6">
                        	<div class="item">
                            	<a target="_blank" href="userinfo.php?uid={$item['id']}" class="link"></a>
                            	<div class="user-img-name">
                                	<img src="{$path}{$item['photo']}" class="img-yuan-x36">
                                	<span class="user">{$item['user']}</span>
                                	<span class="nick">{$item['nick']}</span>
                                    <span class="{$stat1}-status"></span>
                            	</div>
                           		<div class="user-info">
                                	<div class="text-overflow">{$item['qianming']}</div>
                                	<div class="guanzhu-fans">
	                                    <span>
	                                        <em>关注：</em>
	                                        <i>{$guanzhu1}</i>
	                                    </span>
	                                    <span>
	                                        <em>粉丝：</em>
	                                        <i>{$fensi1}</i>
	                                    </span>
	                                </div>
                                	<div class="level-push">
	                                    <span>
	                                        <em>等级：</em>
	                                        <i>暂无等级</i>
	                                    </span>
	                                    <span>
	                                        <em>发帖数：</em>
	                                        <i>{$count1}</i>
	                                    </span>
                                	</div>
	                                <div class="new-post">
	                                    <div class="text-overflow">
                                        <a target="_blank" href="details.php?cid={$newcont1['id']}">{$newcont1['title']}</a>
                                        </div>
	                                    <div><em>{$newcont1['time']}</em></div>
	                                </div>
	                            </div>
                            </div>
                        </div>
                    
b;
    }

}
             $c= <<<c
                </div>
            </div>
            <div class="guanzhu-me">
                <div class="title">关注我的人<b class="r pull"></b></div>
                    <div class="content row">
c;
$fans = json_decode($user_data['follow_me'])->uids;
if(!$fans){
            $d = <<<d
                <div class="no-content">
                    空空如也
                </div>
d;
}else{
    $fans_uids = implode(',', $fans);
    $data2 = $Db->find([
        table => ['bbs_user'],
        where => "`id` in ($fans_uids)"
    ]);
    foreach ($data2 as $item){
        $stat2 = (time()-$item['last_time'])<1800 ? 'online':'offline';
        $guanzhu2 = count(json_decode($item['my_follow'])->uids);
        $fensi2 = count(json_decode($item['follow_me'])->uids);
        $count2 = $Db->count([
            table => ['content'],
            where => "`uid` = {$item['id']}"
        ]);
        $newcont2 = $Db->find([
        table => ['content'],
        field => 'title,time,id',
        where => "uid = {$item['id']} order by time desc"
        ])[0];
        $newcont2['title'] = htmlspecialchars($newcont2['title']);
        $item = $Db->tohtml($item);
        $d .= <<<d
                        <div class="col-sm-6">
                            <div class="item">
                                <a target="_blank" href="userinfo.php?uid={$item['id']}" class="link"></a>
                                <div class="user-img-name">
                                    <img src="{$path}{$item['photo']}" class="img-yuan-x36">
                                    <span class="user">{$item['user']}</span>
                                    <span class="nick">{$item['nick']}</span>
                                    <span class="{$stat2}-status"></span>
                                </div>
                                <div class="user-info">
                                    <div class="text-overflow">{$item['qianming']}</div>
                                    <div class="guanzhu-fans">
                                        <span>
                                            <em>关注：</em>
                                            <i>{$guanzhu2}</i>
                                        </span>
                                        <span>
                                            <em>粉丝：</em>
                                            <i>{$fensi2}</i>
                                        </span>
                                    </div>
                                    <div class="level-push">
                                        <span>
                                            <em>等级：</em>
                                            <i>暂无等级</i>
                                        </span>
                                        <span>
                                            <em>发帖数：</em>
                                            <i>{$count2}</i>
                                        </span>
                                    </div>
                                    <div class="new-post">
                                        <div class="text-overflow"><a target="_blank" href="details.php?cid={$newcont2['id']}">{$newcont2['title']}</a></div>
                                        <div><em>{$newcont2['time']}</em></div>
                                    </div>
                                </div>
                            </div>
                        </div>
d;
    }             
}
            $e=<<<e
                    </div>
            </div>
            <div class="banmian">
                <div class="title">我收藏的版面<b class="r pull"></b></div>
                <div class="content row">
e;
$module = json_decode($user_data['my_follow'])->mids;
if(!$module){
            $f = <<<f
                <div class="no-content">
                    空空如也
                </div>
f;
}else{
    $module_mids = implode(',', $module);
    $data3 = $Db->find([
        table => ['module'],
        where => "`id` in ($module_mids)"
    ]);
    
    foreach ($data3 as $item){
    //今日
    $today_cnt = $Db->count([
        table => [content => 'a',module => 'b'],
        where => "a.mid = b.id and b.id = {$item['id']} and a.time > CURDATE()"
    ]);
    //主题
    $main_cnt = $Db->count([
        table => [content => 'a',module => 'b'],
        where => "a.mid = b.id and b.id = {$item['id']} and a.cid = 0"
    ]);
    //总数
    $all_cnt = $Db->count([
        table => [content => 'a',module => 'b'],
        where => "a.mid = b.id and b.id = {$item['id']}"
    ]);
    //版务
    $man = json_decode($item['manager'])->uids;
    $man_uids = implode(',', $man);
    if(!$man_uids){
        $man_uids = 0;
    }
    $man_data = $Db->find([
        table => ['bbs_user'],
        field => 'id,user',
        where => "id in ({$man_uids})"
    ]);
    $man_data = $Db->tohtml($man_data);
    if($man_data){
        $manager_list = '';
        foreach ($man_data as $man_item) {
             $manager_list .= "<a href='/userinfo.php?uid={$man_item['id']}'>{$man_item['user']}</a>";
        }
    }else{
        $manager_list = '<span class="icolor">暂无版务</span>';
    }
    //最新动态
    $cont_data = $Db->find([
        table => [content => 'a',module => 'b',bbs_user => 'c'],
        field => 'a.id,a.time,a.title,a.time,c.id uid,c.user,c.photo',
        where => "a.mid = b.id and a.uid = c.id and b.id = {$item['id']} and a.delete_time is NULL order by a.time desc limit 0,1"
    ])[0];
    $cont_data = $Db->tohtml($cont_data);
    if($cont_data){
        $new_cont = <<<new
        <a href="userinfo.php?uid={$cont_data['uid']}" class="l"><img class="img-yuan-x36" src="{$path}{$cont_data['photo']}"></a>
      <div class="l content2">
        <div class="content-title">
          <a href="details.php?cid={$cont_data['id']}">{$cont_data['title']}</a>
        </div>
        <div class="content-time">
          <span>{$cont_data['user']} {$cont_data['time']}</span>
        </div>
      </div>
new;
    }else{
        $new_cont = '<span class="icolor">暂无动态</span>';
    }
    $item = $Db->tohtml($item);
        $f .= <<<f
        <div class="module-info clearfix">
          <a href="module.php?mid={$item['id']}" class="link"></a>
          <div class="col-sm-6">
            <div class="module-title"><span class="tt1">{$item['name']}</span></div>
            <div class="module-label">{$item['info']}</div>
            <div class="module-main">
              <span>今日：{$today_cnt}</span>
              <span>主题：{$main_cnt}</span>
              <span>帖数：{$all_cnt}</span>
            </div>
            <div class="module-manager">
              <span>版务：</span>
              {$manager_list}
            </div>
          </div>
          <div class="col-sm-6">
            <div class="content-push clearfix">
              {$new_cont}
            </div>
          </div>
        </div>
f;
    }             
}
            $g=<<<g
                </div>
            </div>
            <div class="tiezi">
                <div class="title">我收藏的帖子<b class="r pull"></b></div>
                <div class="content row">
g;
$content = json_decode($user_data['my_follow'])->cids;
if(!$content){
            $h = <<<h
                <div class="no-content">
                    空空如也
                </div>
h;
}else{
    $content_cids = implode(',', $content);
    $data4 = $Db->find([
        table => ['content'],
        where => "`id` in ($content_cids) and delete_time is NULL"
    ]);
    if($data4){
    foreach ($data4 as $item){
        $user_data = $Db->find([
            table => [content => 'a',bbs_user => 'b'],
            field => 'b.id,b.user,b.photo',
            where => "a.uid = b.id and a.id = {$item['id']}" 
        ])[0];
        $user_data = $Db->tohtml($user_data);
        $item['title'] = htmlspecialchars($item['title']);
        $h .= <<<h
        <div class="module-info clearfix">
          <a href="details.php?cid={$item['id']}" class="link"></a>
          <div class="col-sm-6">
            <div class="module-main2">
              <span>回复：{$item['reply_num']}</span>
              <span>浏览：{$item['look_num']}</span>
            </div>
            <div class="content-time">
                <span>{$item['time']}</span>
            </div>
          </div>
          <div class="col-sm-6">
            <div class="content-push clearfix">
              <a href="userinfo.php?uid={$user_data['id']}" class="l"><img class="img-yuan-x36" src="{$path}{$user_data['photo']}"></a>
              <div class="l content2">
                <div class="content-title icolor">
                  {$item['title']}
                </div>
                <div class="content-time">
                  <span>{$user_data['user']}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
h;
    }  
    }else{
        $h = <<<h
                <div class="no-content">
                    空空如也
                </div>
h;
    }           
}
            $i=<<<i
                </div>
            </div>
        </div> 

        <script>
        // 面板收放
		let title_bars = $('#guanzhu-collect .title');
		let open = [];
		let orgin_h = [];
		let timer = null;
		let title_bars_len = title_bars.length;
		for(var i = 0;i < title_bars_len;i++){
		    open[i] = true;
		    orgin_h[i] = $("#guanzhu-collect .content:eq("+(i)+")").height();
		}
		title_bars.click(function(){
		    let i = $(this).index('#guanzhu-collect .title');
		    $("#guanzhu-collect .pull:eq("+(i)+")").toggleClass('open');
		    let content = $("#guanzhu-collect .content:eq("+(i)+")");
		    let danwei_s = open[i] ? -10 : 10;
		    let danwei_t = 200*danwei_s/orgin_h[i];
		    if(!open[i]){
		        content.css('display','block')
		    }
		    clearInterval(timer);
		    timer = setInterval(function(){
		        let h = content.height();
		        h += danwei_s;
		        if(h > orgin_h[i]){
		            h = orgin_h[i];
		            clearInterval(timer)
		        }else if(h < 0){
		            h = 0;
		            content.css('display','none');
		            clearInterval(timer)
		        }
		        content.height(h);
		    },danwei_t);
		    open[i] = !open[i];
		});
		// 版块颜色轮换
		let color_left = ['left-a','left-b','left-c','left-d'];
		let color_top = ['top-a','top-b','top-c','top-d'];
		let items = document.querySelectorAll('#guanzhu-collect .item');
		let new_posts = document.querySelectorAll('#guanzhu-collect .new-post');
		let itmes_len = items.length;
		for(let i = 0;i < itmes_len;i++){
		    let j = i % 4;
		    items[i].className += ' '+color_left[j];
		    new_posts[i].className += ' '+color_top[j];
		}
        // 版块颜色轮换
        let module_info = document.querySelectorAll('.module-info');
        let module_info_len = module_info.length;
        for(let i = 0;i < module_info_len;i++){
          let j = i % 4;
          module_info[i].className += ' '+color_left[j];
        }
        </script>       
i;
$html = $a.$b.$c.$d.$e.$f.$g.$h.$i;
		break;

	case 'udinfo':
        $user_data = $Db->tohtml($user_data);
		$man = $user_data['sex']=='男'?'checked':'';
		$woman = $user_data['sex']=='男'?'':'checked';
		$html = <<<html
        <form method="post">
        <div id="ud-info">
            <div class="tt">
                <span>修改信息</span> 
                <a href="pwdsafe.php">修改密码</a>
            </div>
            <div class="main">
                <div>
                    <label class="input-label" for="nick">昵称</label>
                    <input type="text" placeholder="不超过10个字符" name="nick" class="form-control input-sm input bx" id="nick" value="{$user_data['nick']}">
                </div>
                <div>
                    <label class="input-label">性别</label>
                    <label for="sex-man" class="sex-all"><span class="kuang {$man}"></span><span class="sex">男</span></label>
                    <label for="sex-woman" class="sex-all"><span class="kuang {$woman}"></span><span class="sex">女</span></label>
                    <input type="radio" name="sex" id="sex-man" value="1" class="unvisiable" {$man}>
                    <input type="radio" name="sex" id="sex-woman" value="0" class="unvisiable" {$woman}>
                </div>
                <div>
                    <label class="input-label" for="qianming">个性签名</label>
                    <textarea placeholder="不能超过50个字符" name="qianming" id="qianming" class="form-control" rows="3">{$user_data['qianming']}</textarea>
                </div>
                <div>
                    <label class="input-label" for="phone">联系电话</label>
                    <input type="text" name="phone" class="form-control input-sm input" id="phone" value="{$user_data['phone']}">
                </div>
            </div>
            <button name="submit" id="submit">修改</button>
        </div>
        </form>
        <script>
        	//   单选框
			let sex = $('.sex-all');
			let kuang = $('.kuang');
			sex.click(function(){
			    kuang.toggleClass('checked')
			});
			//表单验证
		let input = document.querySelectorAll('#nick,#phone,#qianming');
		$(input).keydown(function(){
		    $(this).removeClass('err')
		});
		$('#submit').click(function(e){
		    let err = true;
		    let nick = $('#nick');
		    let phone = $('#phone');
		    let qianming = $('#qianming');
		    if($.trim(nick.val()) == '' || nick.val().length > 10){
		      nick.focus();
		      nick.addClass('err');
		    }else if( phone.val() !=='' && !/[0-9]{7,}/.test(phone.val())){
		      phone.focus();
		      phone.addClass('err')
		    }else if(qianming.val().length>50){
		        qianming.focus();
		        qianming.addClass('err')
		    }else{
		        err = false;
		    }
		    if(err){
		        e ? e.preventDefault() : window.e.returnValue = false;
		    }
		});
        </script>            
html;
		break;
}
}
if($html){
	echo $html;
}else{
	http_response_code(404);
	echo '<h1 style="color:#337ab7">千呼万唤始出来,犹抱琵琶半遮面</h1>';
}

$Db->close();